package com.itheima.reggie.controller;

import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.common.SmsTemplate;
import com.itheima.reggie.domain.User;
import com.itheima.reggie.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@Slf4j
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private HttpSession httpSession;

    @Autowired
    private SmsTemplate smsTemplate;

    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping("/user/sendMsg")
    public ResultInfo sendMsg(@RequestBody Map<String,String> map){
        String phone = map.get("phone");
        //String code = RandomUtil.randomNumbers(6);
        //todo 固定验证码方便测试
        String code="123";
        log.info("验证码是"+code);
       // httpSession.setAttribute("SMS_"+phone,code);
        //todo
        redisTemplate.opsForValue().set("SMS_"+phone,code,5, TimeUnit.MINUTES);
        //smsTemplate.sendSms(phone,code);
        return ResultInfo.success(null);
    }
    @PostMapping("/user/login")
    public ResultInfo login(@RequestBody Map<String,String> map){
        String phone = map.get("phone");
        String code = map.get("code");
        String codeFrom = (String) redisTemplate.opsForValue().get("SMS_"+phone);
        if (!StringUtils.equals(code,codeFrom)
                || StringUtils.isEmpty(code)
                || StringUtils.isEmpty(codeFrom)
        ) {
            return ResultInfo.error("验证码错误");
        }
        User user=userService.findByPhone(phone);
        if (user!=null){
            
        }else {
            user= new User();
            user.setPhone(phone);
            user.setStatus(1);
            userService.save(user);
        }
       httpSession.setAttribute("SESSION_USER", user);
        return ResultInfo.success(user);
    }
}
